package com.wzcl.app.controller.student;

import com.wzcl.app.dao.model.Cart;
import com.wzcl.app.model.common.MyPage;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.model.dto.CartDto;
import com.wzcl.app.model.vo.CartVo;
import com.wzcl.app.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@RestController
@RequestMapping("/cart")
@Api(value = "用户购物车管理controller", tags = {"用户购物车管理接口"})
public class CartController {

    @Resource
    private CartService cartService;

    @ApiOperation("加入购物车")
    @PostMapping("/add")
    public RVO<CartVo> addCart(@RequestBody @Valid CartDto cartDto){
        cartDto.setPhone(SecurityContextHolder.getContext().getAuthentication().getName());
        Cart cart = cartService.addCart(cartDto);
        return RVO.success(CartVo.create(cart));
    }

    @ApiOperation("删除购物车项")
    @PostMapping("/del")
    public RVO delCart(@RequestBody List<CartDto> cartDtos) {
        ArrayList<Cart> list = new ArrayList<>();
        for (int index = 0; index <cartDtos.size(); index++) {
            cartDtos.get(index).setPhone(SecurityContextHolder.getContext().getAuthentication().getName());
            Cart cart = cartService.delPhysicalCart(cartDtos.get(index));
            list.add(cart);
        }
        return RVO.success(list);
    }

    @ApiOperation("获取用户购物车信息")
    @PostMapping("/getList")
    public RVO<List<CartVo>> getCart(@RequestBody CartDto cartDto){
        cartDto.setPhone(SecurityContextHolder.getContext().getAuthentication().getName());
        List<Cart> list = cartService.getCartList(cartDto);
        if(list != null && list.size()>0){
            List<CartVo> collect = list.stream().map(CartVo::create).collect(Collectors.toList());
            return RVO.success(collect);
        }
        return RVO.success(null);
    }

    @ApiOperation("分页获取用户购物车信息")
    @PostMapping("/getPage")
    public RVO<List<CartVo>> getCartByPage(@RequestBody CartDto cartDto){
        cartDto.setPhone(SecurityContextHolder.getContext().getAuthentication().getName());
        MyPage<Cart> page = cartService.getCartPage(cartDto);
        if(page != null && page.getContent().size()>0){
            List<CartVo> collect = page.getContent().stream().map(CartVo::create).collect(Collectors.toList());
            return RVO.success(collect,page);
        }
        return RVO.success(null);
    }
}
